package com.kingjw.lease.web.admin.custom.interceptor;

import com.kingjw.lease.common.login.LoginUser;
import com.kingjw.lease.common.login.LoginUserHolder;
import com.kingjw.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 身份认证拦截器
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    /**
     * 和前端约定好，前端登录后，后续请求都将JWT 放置于HTTP请求的Header中，其Header的key为`access-token`
     *
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return 返回true 则表示可以正常调用后续的方法运行，返回false 则不会继续处理
     *          这里因为有问题会抛出异常，所以不用专门返回false
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access-token");

        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        // 将用户名和用户id 放在本地线程，就不需要再获取用户个人信息时做两次token 的校验
        LoginUserHolder.setLoginUser(new LoginUser(userId, username));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}